package com.course.rabbitmq.consumer;

import com.common.handler.ExchangeServiceHandler;
import com.common.tool.EmailTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.*;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

/**
 * 异常处理交换机
 */
@Component
@Slf4j
public class ErrorConsumer {

    @Resource
    EmailTool emailTool;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "course-error-queue" , durable = "true" , arguments = @Argument(name = "x-queue-mode" , value = "lazy")), // 持久化队列 开启惰性队列
            exchange = @Exchange(name = ExchangeServiceHandler.ERROR_EXCHANGE, type = ExchangeTypes.DIRECT),
            key = "course.error.message"
    ))
    public void error(Object msg){
        Message message = (Message) msg;
        MessageProperties messageProperties = message.getMessageProperties();
        String errorStackMessage = messageProperties.getHeader("x-exception-stacktrace").toString();    // 错误信息
        // 通知开发者进行解决
        emailTool.sendEmail("course-service-error-exchange",errorStackMessage,"2315912943@qq.com");
        log.error("rabbit-mq-异常处理交换机: queue:{}  错误信息为：{}", "course-error-queue",errorStackMessage);
        log.error("rabbit-mq-异常处理交换机: queue:{} 源数据信息：{}", "course-error-queue",new String(message.getBody()));
    }
}
